import axios from 'axios';
import type { ChartItem, StatisticItem } from '../types';

// 创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 30000
});

// 添加响应拦截器
request.interceptors.response.use(
  response => response,
  error => {
    if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
      // 超时处理
      console.error('请求超时，请重试');
    }
    return Promise.reject(error);
  }
);

interface DateRange {
  startTime: string;
  endTime: string;
}

interface RequestParams {
  task_name: string;
  start_time?: string;
  end_time?: string;
}

interface ResponseItem {
  name: string;
  value: string;
}

interface ApiResponse {
  code: number;
  message: string;
  data: {
    items: ResponseItem[];
  };
}

// API接口
export const api = {
  // 获取统计数据
  getStatistics: async (params: RequestParams) => {
    try {
      const response = await request.post<ApiResponse>('/api/precise_ent_call/statistics/connection_rate', params);
      return response;
    } catch (error) {
      console.error('获取统计数据失败:', error);
      throw error;
    }
  },

  // // 获取总览图表数据
  // getOverviewCharts: (params: RequestParams) => {
  //   return request.post<ChartItem[]>('/overview-charts', params);
  // },

  // // 获取详细图表数据
  // getDetailCharts: (params: RequestParams) => {
  //   return request.post<ChartItem[]>('/detail-charts', params);
  // }
};

export const getMapData = (params: {
  startTime?: string;
  endTime?: string;
  province?: string;
  city?: string;
}) => {
  // 如果没有传入时间，使用当前时间
  const now = new Date();
  const currentTime = now.toISOString().split('T')[0];
  
  const requestParams = {
    startTime: params.startTime || currentTime,
    endTime: params.endTime || currentTime,
    province: params.province,
    city: params.city
  };

  return request({
    url: '/api/map/data',
    method: 'get',
    params: requestParams
  });
}; 